<template>
  <div class="FileUpload">
    <n-upload :accept="acceptTypes" :show-file-list="false" :custom-request="customRequest">
      <n-button
        style="background: #fff"
        :loading="data.loading"
        :disabled="fileList.length >= limit"
      >
        <n-icon size="14" :component="Upload" style="margin-right: 4px"></n-icon>
        上传文件
      </n-button>
    </n-upload>
    <div class="pointer-events-none mt10 text-12 color-gray">
      可上传{{ acceptText }}格式文件，单个文件不超过{{ fileSize }}M
    </div>
    <FileList v-model="fileList" style="margin-top: 10px" :color="color" />
    <Teleport to="body">
      <n-progress
        v-if="data.showProgress"
        class="center"
        type="circle"
        :percentage="data.percentage"
      />
    </Teleport>
  </div>
</template>
<script setup lang="jsx">
import { useFileStore } from '@/store'
import { Upload } from '@vicons/tabler'
import FileList from './FileList.vue'
defineOptions({ name: 'FileUpload' })
const fileList = defineModel({
  type: Array,
  default: () => [],
})
const props = defineProps({
  accept: {
    type: Array,
    default: () => ['jpg', 'png', 'doc', 'docx', 'xls', 'xlsx', 'pdf', 'ppt', 'pptx', 'mp3', 'mp4'],
  },
  fileSize: {
    type: Number,
    default: 200,
  },
  limit: {
    type: Number,
    default: 9,
  },
  color: {
    type: String,
    default: '#f3f5f8',
  },
})
const acceptTypes = computed(() => props.accept.map((item) => `.${item}`).join(','))
const acceptText = computed(() => props.accept.join('/'))
const fileSizeByte = computed(() => 2 ** 20 * props.fileSize)
const data = reactive({
  loading: false,
  showProgress: false,
  percentage: 0,
})
const fileStore = useFileStore()
function customRequest({ file, onFinish, onError }) {
  if (file.file.size > fileSizeByte.value) {
    $message.warning(`单个文件不能超过${props.fileSize}M!`)
    return false
  }
  data.loading = true
  fileStore
    .upload(file.name, file.file, file.file.size, (p) => {
      data.showProgress = true
      data.percentage = parseFloat((p * 100).toFixed(2))
    })
    .then((res) => {
      fileList.value.push(res)
      onFinish()
    })
    .catch((err) => {
      console.log(err)
      onError()
    })
    .finally(() => {
      data.loading = false
      data.showProgress = false
      data.percentage = 0
    })
}
onBeforeMount(() => {
  fileStore.getFileInfo()
})
</script>
<style lang="scss" scoped>
.center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%);
  z-index: 1000000000000;
}
</style>
